package com.express.service.impl;

import com.express.core.mapper.WxUserMapper;
import com.express.dto.LoginValidateDto;
import com.express.entity.WxUser;
import com.express.service.IWxUserService;
import com.express.util.JwtUtil;
import com.express.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxUserServiceImpl implements IWxUserService {

    @Autowired
    WxUserMapper mapper;
    @Autowired
    private WxUserMapper wxUserMapper;

    @Override
    public int save(WxUser user) {
        return mapper.save(user);
    }

    @Override
    public List<WxUser> query(Map<String,Object> map) {
        return mapper.query(map);
    }

    @Override
    public WxUser getUser(int account, String openId) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",account);
        map.put("openId",openId);
        List<WxUser> wxUsers = wxUserMapper.query(map);
        if(!ObjectUtils.isEmpty(wxUsers)){
            return wxUsers.get(0);
        }
        return null;
    }

    @Override
    public int delete(WxUser user) {
        return mapper.delete(user);
    }

    @Override
    public int update(WxUser user) {
        return mapper.update(user);
    }

    @Override
    public TokenVo validate(LoginValidateDto validateDto) {
        TokenVo vo = null;
        try {
            WxUser wxUser = getUser(validateDto.getAccount(),validateDto.getPwd());
            if(!ObjectUtils.isEmpty(wxUser)){
                vo = new TokenVo();
                vo.setToken(JwtUtil.createToken(wxUser));
                vo.setAccount(wxUser.getId()+"");
                vo.setName(wxUser.getNickName());
                vo.setLoginTime(new Date());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }

}
